package com.gu.qqdemo.frg;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import com.gu.qqdemo.R;
import com.gu.qqdemo.utils.app.BaseFragment;

public class MainActityFragment extends BaseFragment {
    private FrameLayout fl;//fragment碎片，framelayout帧布局
    private RadioGroup rg;


    private BaseFragment[] frag;
    //已经添加过的 fragment
    private BaseFragment[] frag_add;


    @Override
    protected int getLayoutId() {

        return 0;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View v = inflater.inflate(R.layout.frag_main, container, false);
        fl = v.findViewById(R.id.fl);
        rg = v.findViewById(R.id.rg);
        return v;
    }

    @Override
    protected void initData() {
        frag_add = new BaseFragment[]{new MainFragment(), new MainFragment2(), new MainFragment3()};
        frag = new BaseFragment[3];

    }

    @Override
    protected void initListener() {
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb1: {
                        changeFragment(0);
                    }
                    break;
                    case R.id.rb2: {
                        changeFragment(1);
                    }
                    break;
                    case R.id.rb3: {
                        changeFragment(2);
                    }
                    break;
                }
            }
        });
        //默认选中消息栏
        rg.check(R.id.rb1);
    }


    private void changeFragment(int index) {
        FragmentTransaction tran = getChildFragmentManager().beginTransaction();
        for (Fragment fg : frag) {
            if (fg != null)
                tran.hide(fg);
        }
        if (frag[index] == null) {
            frag[index] = frag_add[index];
            tran.add(R.id.fl, frag[index]);
        } else {
            tran.show(frag[index]);
        }
        tran.commit();
    }


}
